#include "RegisterDriveWindow.h"

///Copyright (c) 2009-2010 T. Klepzig 

RegisterDriveWindow::RegisterDriveWindow(LPVOID parent)
{
	this->parent = parent;
	drivePluggedIn = 0;
}


RegisterDriveWindow::~RegisterDriveWindow()
{
}

void RegisterDriveWindow::Create(HINSTANCE hInstance)
{
	Window::Create(hInstance, TEXT("RegisterDriveWndClass"), WndProc, WS_EX_TOPMOST | WS_EX_DLGMODALFRAME, WS_SYSMENU | WS_CAPTION, 0, 0, 0, LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)));
	
	this->SetText(Translate(2, TEXT("Waiting for device"), TEXT("#...")));
	this->SetSize(300, 150);
}

void RegisterDriveWindow::Show()
{
	POINT pos = Utilities::CenterScreen(300, 150); 
	this->SetLocation(pos);

	Window::Show();
}

void RegisterDriveWindow::DrivePluggedIn(RDWNDEVENTPROC ptr)
{
	drivePluggedIn = ptr;
}



LRESULT CALLBACK RegisterDriveWindow::WndProc(LPVOID sender, HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{	
	switch (uMsg)
	{	
	case WM_PAINT:
		{
			HDC          hdc;
			PAINTSTRUCT  ps;

			hdc = BeginPaint(hWnd, &ps);
			
			RECT clientRect;
			GetClientRect(hWnd, &clientRect);

			Utilities::DrawDefaultText(clientRect, hdc, Translate(2, TEXT("Please plug in the device"), TEXT("#...")).c_str(), 14, RGB(0, 0, 0), DT_CENTER | DT_VCENTER | DT_SINGLELINE, FW_BOLD);

			EndPaint(hWnd, &ps);

			break;
		}
	case WM_DEVICECHANGE:
		{
			if (instances[hWnd]->IsVisible() && wParam == DBT_DEVICEARRIVAL)
			{
				DEV_BROADCAST_HDR *hdr = (DEV_BROADCAST_HDR*)lParam;

				if (hdr->dbch_devicetype == DBT_DEVTYP_VOLUME)
				{
					DEV_BROADCAST_VOLUME *volume = (DEV_BROADCAST_VOLUME*)lParam;

					TCHAR driveLetter = Utilities::GetVolumeLetter(volume->dbcv_unitmask);
					DWORD serial = Utilities::GetVolumeSerial(driveLetter);

					if (((RegisterDriveWindow*)instances[hWnd])->drivePluggedIn)
					{
						((RegisterDriveWindow*)instances[hWnd])->drivePluggedIn((RegisterDriveWindow*)instances[hWnd], driveLetter, serial, ((RegisterDriveWindow*)instances[hWnd])->parent, ((RegisterDriveWindow*)instances[hWnd])->tag);
						instances[hWnd]->Hide();
					}
				}
			}

			break;
		}
	case WM_CLOSE:
		{
			instances[hWnd]->Hide();
			return 0;
		}
	}

	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}